package cn.thr.pethome.fastdfs.controller;


import cn.thr.pethome.util.AjaxResult;
import cn.thr.pethome.util.BusinessException;
import cn.thr.pethome.util.FastdfsUtil;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fast")
//这里是说明你这个类是干什么用的
@Api(value = "文件上传API", description = "文件上传下载的功能")
public class FastDFSController {
    //上传

    /**
     * @param file
     * @return
     * @RequestPart 请求参数认证  required = true 必传   value = "file" 前端请求的参数名叫file
     */
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true, value = "file") MultipartFile file) {
        try {
            byte[] bytes = file.getBytes();
            String filename = file.getOriginalFilename();//上传的文件的名字 全名 包含了后缀名
            String suffix = filename.substring(filename.lastIndexOf(".") + 1);//包含了.的
            String uploadPath = FastdfsUtil.upload(bytes, suffix);//返回的就是上传文件的路径//包含组的
            return AjaxResult.success().setData(uploadPath);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error().setMsg("网络异常，请联系管理员");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error().setMsg("网络异常，请稍后再试");
        }
    }

    //删除
    public AjaxResult delete(@RequestParam(required = true, value = "path") String path) {
        try {
            //截取路径
            //传进来的路径  /group1/M00/03/68/CgAIC2O5aK2AdzXRAH3ejPKDVYY179.jpg
            //处理第一个斜杆
            String filePath = path.substring(1);
            //处理组
            String group = filePath.substring(0, filePath.indexOf("/"));
            String bodyPath = filePath.substring(filePath.indexOf("/") + 1);
            FastdfsUtil.delete(group, bodyPath);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("网络异常，请联系管理员");
        }
    }
}
//下载
